
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from logger import get_module_logger
logger = get_module_logger('docker')

from flask import Blueprint,  request, jsonify,render_template,session
from decorator import login_required
from bt import Bt_api
blueprint = Blueprint('/docker', __name__, url_prefix='/docker')

@blueprint.route("/docker_shop", methods=['GET', 'POST'])
@login_required
def docker_shop():

    return render_template('docker_shop.html')


# 获取容器商店列表数据
@blueprint.route("/api/shop_list", endpoint='get_shop_list', methods=['GET'])
@login_required
def get_shop_list():
    # 定义容器商店列表数据
    shop_list = [
        {
            "id": 1,
            "name": "ESP-AI服务端",
            "description": "ESP-AI是一个基于esp32s3开发的智能对话机器人，类似小爱同学",
            "image_url": "https://wmimg.com/i/113/2024/06/665c706e14480.png",
            "icon": "mdi-robot",
            "color": "success",
            "install_url": "/docker/install/1"
        },
        {
            "id": 2,
            "name": "MySQL数据库",
            "description": "开源关系型数据库管理系统，广泛用于Web应用",
            "image_url": "{{cdn}}/static/images/mysql-demo.jpg",
            "icon": "mdi-database",
            "color": "info",
            "install_url": "/docker/install/2"
        },
        {
            "id": 3,
            "name": "Nginx服务器",
            "description": "高性能Web服务器和反向代理服务器",
            "image_url": "{{cdn}}/static/images/nginx-demo.jpg",
            "icon": "mdi-web",
            "color": "warning",
            "install_url": "/docker/install/3"
        },
        {
            "id": 4,
            "name": "Redis缓存",
            "description": "高性能的键值对数据库，常用于缓存和消息队列",
            "image_url": "{{cdn}}/static/images/redis-demo.jpg",
            "icon": "mdi-memory",
            "color": "danger",
            "install_url": "/docker/install/4"
        },
        {
            "id": 5,
            "name": "MongoDB数据库",
            "description": "基于分布式文件存储的开源数据库系统",
            "image_url": "{{cdn}}/static/images/mongodb-demo.jpg",
            "icon": "mdi-leaf",
            "color": "success",
            "install_url": "/docker/install/5"
        }
    ]
    
    return jsonify({
        "status": True,
        "data": shop_list,
        "msg": "获取成功"
    })


# 安装应用
@blueprint.route("/install/<int:app_id>", endpoint='install_app', methods=['POST'])
@login_required
def install_app(app_id):
    # 获取表单数据
    name = request.form.get('name')
    port = request.form.get('port')
    
    # 验证名称格式: username + appName
    username = session.get('username')
    if not username:
        return jsonify({
            "status": False,
            "msg": "用户未登录"
        })
    
    # 检查名称是否符合格式要求
    if not name or not name.startswith(username):
        return jsonify({
            "status": False,
            "msg": "应用名称格式不正确，应为: " + username + "应用名称"
        })
    
    # 执行通用的安装逻辑
    result = install_app_generic(name, port, app_id,session.get('bt_fife'))
    
    return jsonify(result)


def install_app_generic(name, port, app_id, path):
    """通用应用安装逻辑"""
    try:
        # 根据应用ID获取应用名称和对应的Docker Compose配置
        app_configs = {
            1: {
                "name": "ESP-AI服务端",
                "compose": f"""version: '3'
services:
esp-ai:
    image: esp-ai:latest
    ports:
    - "{port}:8080"
    volumes:
    - .{path}/index.js:/host/index.js
    command: sh -c "cp /host/index.js {path} && node /opt/espai/index.js"
    restart: unless-stopped
                    """
                                },
            2: {
                "name": "MySQL数据库",
                "compose": """version: '3'
services:
  mysql:
    image: mysql:8.0
    ports:
      - "${port}:3306"
    volumes:
      - ./mysql_data:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=rootpassword
      - MYSQL_DATABASE=${name}
"""
            },
            3: {
                "name": "Nginx服务器",
                "compose": """version: '3'
services:
  nginx:
    image: nginx:latest
    ports:
      - "${port}:80"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf
      - ./www:/usr/share/nginx/html
"""
            },
            4: {
                "name": "Redis缓存",
                "compose": """version: '3'
services:
  redis:
    image: redis:latest
    ports:
      - "${port}:6379"
    volumes:
      - ./redis_data:/data
"""
            },
            5: {
                "name": "MongoDB数据库",
                "compose": """version: '3'
services:
  mongodb:
    image: mongo:latest
    ports:
      - "${port}:27017"
    volumes:
      - ./mongo_data:/data/db
    environment:
      - MONGO_INITDB_ROOT_USERNAME=admin
      - MONGO_INITDB_ROOT_PASSWORD=password
"""
            }
        }
        
        # 获取应用配置
        app_config = app_configs.get(app_id)
        if not app_config:
            return {'status': False, 'msg': '未知的应用ID'}
        
        app_name = app_config["name"]
        compose_template = app_config["compose"]
        
        # 替换Docker Compose模板中的变量
        compose_content = compose_template.replace("${name}", name).replace("${port}", port)
        
        # 实例化宝塔API对象
        bt_api = Bt_api(session.get('bt_url'), session.get('bt_key'))
        
        # 开放端口
        port_result = bt_api.open_port(port, f"{name} {app_name}端口")
        logger.debug(f"Port result: {port_result}")
        # 检查端口开放结果，注意status可能是布尔值或字符串
        if isinstance(port_result.get('status'), bool) and not port_result['status']:
            return {'status': False, 'msg': port_result.get('msg', '端口开放失败')}
        elif isinstance(port_result.get('status'), str) and port_result['status'].lower() == "false":
            return {'status': False, 'msg': port_result.get('msg', '端口开放失败')}
        
        # 生成Docker Compose文件内容
        # 新建Compose文件
        bt_api=Bt_api(session.get('bt_url'),session.get('bt_key'))
        data = bt_api.CreateFile(session.get('bt_fife')+"/docker-compose.yml")
        # 编辑文件
        data = bt_api.SaveFileBody(data=compose_content, path=session.get('bt_fife')+"/docker-compose.yml")
        
        
        return {
            "status": True,
            "msg": f"{app_name} '{name}' 安装成功，端口 {port} 已开放，应用已启动",
            "details": {
                "app_name": name,
                "port": port,
                "port_result": port_result,
           
            }
        }
    except Exception as e:
        return {
            "status": False,
            "msg": f"{app_name}安装失败: {str(e)}"
        }

# 开放端口
@blueprint.route("/docker_port", endpoint='docker_port',methods=['GET', 'POST'])
@login_required
def docker_port():
    if request.method == 'POST':
        port = request.form.get('port')
        brief = request.form.get('brief')
        # 实例化宝塔API对象
        bt_api=Bt_api(session.get('bt_url'),session.get('bt_key'))
        data = bt_api.open_port(port,brief)
        
    
        return jsonify(data)
    return jsonify({'code': 401, 'msg': '错误'})

            